import { AntDesignTheme } from '@amcax/base';
import { ProductTreeNode } from '@app-cad-env/product/widgets/LeftPanel/types';
import { PRODUCT_EVENT } from '@app-cad/common/Constants';
import { ctx2, userEvents } from '@app-cad/module';
import { ConfigProvider, Form, Input, InputRef, Modal } from 'antd';
import React, { useEffect, useRef, useState, KeyboardEvent } from 'react';

interface RenameDocModalProps {
  open: boolean;
  onClose: () => void;
  treeNode: ProductTreeNode | undefined;
}

const RenameDocModal: React.FC<RenameDocModalProps> = ({
  open,
  onClose,
  treeNode,
}) => {
  const [loading, setLoading] = useState(false);

  const [formValid, setFormValid] = useState(false);
  const [form] = Form.useForm();
  const inputRef = useRef<InputRef>(null);

  useEffect(() => {
    if (open && inputRef.current) {
      form.resetFields();
      form.setFieldsValue({ newName: treeNode?.title });
      setTimeout(() => {
        inputRef.current?.focus();
        inputRef.current?.select();
      }, 0);
    }
  }, [treeNode, form, open]);

  const handleOk = async () => {
    const { newName } = await form.validateFields();
    setLoading(true);

    try {
      await ctx2.commandCenters.basicCommands.setLabel(
        treeNode.key,
        newName.trim(),
      );

      treeNode.parent.children.find((item) => item.key === treeNode.key).title =
        newName;
      userEvents.emit(PRODUCT_EVENT.RENAME_DOC);
    } finally {
      setLoading(false);
      onClose();
    }
  };

  const handleValuesChange = () => {
    form
      .validateFields()
      .then((values) => {
        if (values.newName.trim() === treeNode.title) {
          setFormValid(false);
        } else {
          setFormValid(true);
        }
      })
      .catch(({ errorFields }) => setFormValid(!errorFields?.length));
  };

  return (
    <ConfigProvider theme={AntDesignTheme}>
      <Modal
        open={open}
        closable={!loading}
        width={480}
        title='重命名'
        onOk={handleOk}
        okText='确认'
        okButtonProps={{ disabled: !formValid }}
        confirmLoading={loading}
        onCancel={onClose}
        cancelText='取消'
        cancelButtonProps={{ disabled: loading }}
        maskClosable={false}
      >
        <Form
          form={form}
          disabled={loading}
          name='rename_form'
          onValuesChange={handleValuesChange}
        >
          <Form.Item
            name='newName'
            rules={[
              {
                required: true,
                message: '名称不能为空',
              },
            ]}
          >
            <Input
              ref={inputRef}
              onPressEnter={(e?: KeyboardEvent<HTMLInputElement>) => {
                e.stopPropagation();
                handleOk();
              }}
            />
          </Form.Item>
        </Form>
      </Modal>
    </ConfigProvider>
  );
};

export default RenameDocModal;
